package cn.wolfcode.wolf2w.business.listener;

import cn.wolfcode.wolf2w.business.api.domain.Strategy;
import cn.wolfcode.wolf2w.business.service.IStrategyService;
import cn.wolfcode.wolf2w.common.redis.service.RedisService;
import cn.wolfcode.wolf2w.common.redis.util.RedisKeys;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*程序初始化监听器*/
/*格局泛型监听程序准备完成的时机点
    ApplicationReadyEvent--一次*/
@Component
public class ApplicationInitListener implements ApplicationListener<ApplicationReadyEvent>  {
    @Resource
    private IStrategyService strategyService;
    @Resource
    private RedisService redisService;

    //当应用程序事件（应用程序准备完成事件）到达时触发这个方法
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        //查询攻略信息
        List<Strategy> list = strategyService.list();
        //遍历
        for (Strategy strategy : list) {
            String key = RedisKeys.STRATGE_STATIS_HASH.join(strategy.getId().toString());
            if (redisService.hasKey(key)){
                //如果redis中有数据，则使用redis，因为redis中是新的
                continue;
            }
            //没有数据，则使用mysql数据库往redis中存
            Map<String, Object> map = new HashMap<>();
            //阅读量
            map.put("viewnum", Integer.valueOf(strategy.getViewnum().toString()));
            //回复量
            map.put("replynum", Integer.valueOf(strategy.getReplynum().toString()));
            //分享量
            map.put("sharenum", Integer.valueOf(strategy.getSharenum().toString()));
            //点赞量
            map.put("favornum", Integer.valueOf(strategy.getFavornum().toString()));
            //收藏量
            map.put("thumbsupnum", Integer.valueOf(strategy.getThumbsupnum().toString()));
            //攻略id
            map.put("id",strategy.getId());
            //存到redis中
            redisService.setCacheMap(key, map);


        }

    }
}
